package com.tbit.uqbike.client.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.tbit.common.entity.PushMsgLog;
import com.tbit.mqmsgtbl.service.MqMsgService;
import com.tbit.uqbike.client.constant.GatewayProtocol;
import com.tbit.uqbike.client.constant.RabbitMQData;
import com.tbit.uqbike.client.dao.core.RecordDao;
import com.tbit.uqbike.client.dao.log.PushMsgLogDao;
import com.tbit.uqbike.client.service.MQProducer;
import com.tbit.uqbike.client.service.PushMsgLogService;
import lombok.extern.slf4j.Slf4j;
import me.ahoo.cosid.provider.DefaultIdGeneratorProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * @Author: chen
 * @Description: 消息队列推送日志
 * @Date: 创建于 10:20 2022/11/10
 */
@Slf4j
@Service
public class PushMsgLogServiceImpl implements PushMsgLogService {

    @Autowired
    private PushMsgLogDao pushMsgLogDao;
    @Autowired
    private MQProducer mQProducer;

    @Autowired
    private MqMsgService mqMsgService;
    @Autowired
    private RecordDao recordDao;

    public static void main(String[] args) {

    }

    @Override
    public void insert(PushMsgLog pushMsgLog) {
        pushMsgLog.setCreate_time(new Date());
        pushMsgLog.setUpdate_time(new Date());
        pushMsgLogDao.insert(pushMsgLog);
    }

    @Override
    public PushMsgLog getByOrderNO(Long orderNO) {
        return pushMsgLogDao.getByOrderNO(orderNO);
    }

    @Override
    public void editState(PushMsgLog pushMsgLog) {
        PushMsgLog pushMsgLogDB = pushMsgLogDao.getByOrderNO(pushMsgLog.getBiz_id());
        if (ObjectUtil.isNotEmpty(pushMsgLogDB)) {
            pushMsgLogDao.editState(pushMsgLog);
        } else {
            log.warn("未找到对应的推送记录" + pushMsgLog.getBiz_id());
        }
    }

    @Override
    @Transactional
    public void sendPushLog(String msg, String tableName) {
        /**订单号，后期修改成指定类型的格式*/
        String orderNO = UUID.randomUUID().toString();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgId", GatewayProtocol.LOG_SEND);
        jsonObject.put("orderNO", orderNO);
        jsonObject.put("tableName", tableName);
        jsonObject.put("data", msg);

        log.info("财务日志推送" + jsonObject.toJSONString());
        long logNO = DefaultIdGeneratorProvider.INSTANCE.get("logNO").get().generate();
        mqMsgService.createMsgAndSend(logNO, logNO, "1", RabbitMQData.logexchange, RabbitMQData.logkey, jsonObject.toJSONString(), true);

    }

}
